﻿using Microsoft.Extensions.Logging;
using System.Net.Http;
using System;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Web;

public class ExternalApiService : IExternalApiService
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ILogger<ExternalApiService> _logger;
    private readonly JsonSerializerOptions _jsonOptions;

    public ExternalApiService(
        IHttpClientFactory httpClientFactory,
        ILogger<ExternalApiService> logger)
    {
        _httpClientFactory = httpClientFactory;
        _logger = logger;

        _jsonOptions = new JsonSerializerOptions
        {
            TypeInfoResolver = new DefaultJsonTypeInfoResolver(),
            PropertyNameCaseInsensitive = true,
            NumberHandling = JsonNumberHandling.AllowReadingFromString
        };
    }

    public async Task<ExternalApiResponse> GetExternalDataAsync(
        ChannelConfig channelConfig,
        string openid,
        string id)
    {
        try
        {
            var client = _httpClientFactory.CreateClient("ExternalApi");

            // 设置请求头
            if (!string.IsNullOrEmpty(channelConfig.ExternalApiKey))
            {
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", channelConfig.ExternalApiKey);
            }

            // 构建请求URL（添加 openid 和 id 参数）
            var uriBuilder = new UriBuilder(channelConfig.ExternalApiUrl);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);

            if (!string.IsNullOrEmpty(openid))
            {
                query[channelConfig.OpenidParamName] = openid;
            }

            if (!string.IsNullOrEmpty(id))
            {
                query[channelConfig.IdParamName] = id;
            }

            uriBuilder.Query = query.ToString();
            string requestUrl = uriBuilder.ToString();

            _logger.LogInformation($"Calling external API: {requestUrl}");

            // 调用外部API
            var response = await client.GetAsync(requestUrl);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogError($"External API returned {response.StatusCode}: {response.ReasonPhrase}");
                return new ExternalApiResponse
                {
                    Url = channelConfig.SelfMpurl,
                    X = 30
                };
            }
            // 读取并解析数据
            var content = await response.Content.ReadAsStringAsync();
            var jsonDoc = JsonDocument.Parse(content);
            var root = jsonDoc.RootElement;

            // 提取所需字段
            string url = root.GetProperty("url").GetString() ?? channelConfig.SelfMpurl;
            int x = root.TryGetProperty("x", out var xElement) && xElement.ValueKind == JsonValueKind.Number
                ? xElement.GetInt32()
                : 30;

            return new ExternalApiResponse
            {
                Url = url,
                X = x
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error calling external API");
            return new ExternalApiResponse
            {
                Url = channelConfig.SelfMpurl,
                X = 30
            };
        }
    }
}